package com.game.springbootstart.service.impl;

import com.game.springbootstart.DTO.LoginUser;
import com.game.springbootstart.VO.AdminVO;
import com.game.springbootstart.config.Result;
import com.game.springbootstart.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 检查是否为已登录用户
        if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
            throw new RuntimeException("用户未登录，无法登出");
        }

        // 提取用户 ID
        String userId;
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
            // principal 是一个 LoginUser 对象
            if (auth.getPrincipal() instanceof LoginUser) {
                LoginUser loginUser = (LoginUser) auth.getPrincipal();
                userId = loginUser.getAdmin().getId().toString();
            } else {
                throw new RuntimeException("Authentication principal 不是 LoginUser 类型: " + auth.getPrincipal().getClass().getName());
            }
        } else {
            throw new RuntimeException("不支持的认证类型: " + authentication.getClass().getName());
        }

        // 构造 Redis key 并删除
        String redisKey = "tokens_" + userId;
        redisTemplate.delete(redisKey);

        // 清除 SecurityContext
        SecurityContextHolder.clearContext();
    }
}
